import { ref, reactive, watch, onMounted } from 'vue'
import {
  addNetwork,
  getBeforeNetworkEditSelect,
  networkFieldSelect,
  getNetworkAgencyList,
  getNetworkCode,
} from '@/api/network'
import { getInfoAccount } from '@/api/organize'
import { workModulePricePageSelect } from '@/api/order'
import { ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { phone, verifyPhone, setProvince, setProvince2 } from '@/utils/validate'
import { orderVideoUpload, orderAnnexUpload } from '@/api/upload'
import { useTagsViewStore } from '@/store/modules/tagsView'
import type { FormInstance, UploadFile } from 'element-plus'
import _ from 'lodash'
import useGetNetowrkTypeOptionsService from './services/useGetNetowrkTypeOptionsService'
import { HMessage, HMessageBox } from '@/components/common/message'
import infoTip from '@/config/info-tip'

export default function () {
  // 使用获取网点分类下拉选项服务
  const { getOptions: getNetworkTypeOptions, options: netWorktypeOptions } =
    useGetNetowrkTypeOptionsService

  const TagsViewStore = useTagsViewStore()
  const addrsDom_ser = ref()
  const addrsDom = ref()
  const formRef = ref()
  const formRef2 = ref()
  const router = useRouter()
  const route = useRoute()
  const loadingSave = ref(false)
  const loading = ref(false)
  const dialogContract = ref(false)
  const isPdf = ref()
  const file = ref(null)
  const isInput = ref(true)
  const categoryList = ref([
    { name: '内部网点', id: 1 },
    { name: '外部网点', id: 2 },
  ])
  const typeList = ref([
    { name: '团队', id: 1 },
    { name: '个人', id: 2 },
  ])
  const modules = ref(null)
  const addrs = ref({
    // 地址
    province: '',
    city: '',
    area: '',
    town: '',
  })
  const addrs2 = ref([
    {
      // 地址
      province: '',
      city: '',
      area: '',
      town: '',
    },
  ])
  // 自定义字段
  const defined = ref([])
  const data = ref({
    accountId: '', //网点负责人登录账号ID
    phone: '',
    accountName: '', //网点负责人名称
    address: '',
    area: '',
    province: '',
    city: '',
    town: '',
    category: 1, //网点模式：1-内部网点 2-第三方网点,示例值(1)
    code: '', //网点编码
    delModuleSettlementIds: [], //删除的服务模块结算对象ID
    enableStore: false,
    businessPhone: '',
    contacts: '',
    fieldVals: [
      //网点自定义字段值对象
      // {
      //     "fieldId": null,//	自定义字段表ID
      //     "id": null,//	网点字段值ID，新增不必传，修改必传
      //     "name": "",//字段名称
      // "optVos": [
      //     {
      //       "id": 0,
      //       "optValue": ""
      //     }
      //   ],
      //     "type": null,//字段类型
      //     "value": "",//字段值
      // }
    ],
    id: '', //网点D，新增不必传，修改必传
    moduleSettlements: [], //服务模块结算对象
    name: '', //网点名称
    shorterName: '',
    networkAgencyId: '', //网点机构
    path: '', //接口路径
    publicKey: '', //数据加密公钥
    departmentIds: [], // 网点所属部门ID集合
    serviceAreas: [
      //服务区域对象
      {
        area: '',
        city: '',
        id: null,
        province: '',
        town: '',
      },
    ],
    status: false, //	网点状态：false-启用，true-禁用
    strategy: {
      //网点策略对象
      autoCheckCancelOrder: false, //是否自动审核取消工单：false-人工审核，true-自动审核
      autoCheckEndOrder: false, //是否自动审核申请结单：false-人工审核，true-自动审核
      autoDispatchOrder: true, //是否自动派单 false：关闭，true：启用,示例值(true)
      enableCreateOrder: true, //是否启用新建工单 false：关闭，true：启用,示例值(true)
      enableScanReceive: true, //是否启用扫码收款 false：不启用，true：启用,示例值(true)
      enableUpdateSparePrice: true, //是否启用更改配件价格：false-不允许修改，true-允许修改
      importReceiverVoucher: true, //是否上传收款凭证 false：不用上传，true：必须上传,示例值(true)
      autoSureReceiveOrder: true, // 确认接单策略： false：人工确认，true：自动确认,示例值(true)
      withdrawHandlingFeeStrategy: 1, //提现手续费策略：1-按比例收取，2-每间固定
      handingFeeProportion: 0, //手续费比例，单位为%，当withdrawHandlingFeeStrategy=1时生效
      handingFeeFixedOrder: 0, //每单固定手续费：当withdrawHandlingFeeStrategy=2时生效
      allowWithdrawal: true,
      allowSelectFee: true,
      withdrawEmpRootVos: ['-1'],
      selectFeeEmpRootVos: ['-1'],
      allowManagerHelpWithdraw: true,
      allowSecurityCheck: true, // 是否允许防伪查询：false-关闭查询，true-允许查询
      allowCreateOrder: true, // 是否允许新建工单：false-关闭，true-开启
      allowApplySpare: true, // 是否允许配件申请：false-关闭，true-开启
      allowSelectKnowledgeBase: true, // 是否允许查看知识库：false-关闭，true-开启
      allowUpdateSnCode: true,
      allowSelectAmount: true,
    },
    teamType: 1, //团队类型：1-团队，2-个人
    networkTypeIds: [], //分类id集合
    networkTypeNames: [], //分类名称集合
    networkTypeId: '', //网点分类ID
    networkType: '',
    twoNetworkTypeId: '',
    twoNetworkType: '',
    threeNetworkTypeId: '',
    threeNetworkType: '',
    financeVo: {
      bandName: '',
      bandNo: '',
      businessLicenseImage: '',
      businessLicenseNo: '',
      cardholderName: '',
      settlementType: 1,
    },
    freeAmountPercentage: 0,
  })

  // 初始化data
  // 解决添加数据后,再次添加表单会保留上一次填写的信息
  const initData = () => {
    Object.assign(data.value, {
      accountId: null, //网点负责人登录账号ID
      phone: '',
      accountName: '', //网点负责人名称
      address: '',
      area: '',
      province: '',
      city: '',
      town: '',
      category: 1, //网点模式：1-内部网点 2-第三方网点,示例值(1)
      code: '', //网点编码
      delModuleSettlementIds: [], //删除的服务模块结算对象ID
      enableStore: false, //	是否启用仓库：false-关闭，true-开启
      fieldVals: [
        //网点自定义字段值对象
        // {
        //     "fieldId": null,//	自定义字段表ID
        //     "id": null,//	网点字段值ID，新增不必传，修改必传
        //     "name": "",//字段名称
        // "optVos": [
        //     {
        //       "id": 0,
        //       "optValue": ""
        //     }
        //   ],
        //     "type": null,//字段类型
        //     "value": "",//字段值
        // }
      ],
      id: null, //网点ID，新增不必传，修改必传
      moduleSettlements: [], //服务模块结算对象
      name: '', //网点名称
      shorterName: '',
      networkAgencyId: '', //网点机构
      path: '', //接口路径
      publicKey: '', //数据加密公钥
      serviceAreas: [
        //服务区域对象
        {
          area: '',
          city: '',
          id: null,
          province: '',
          town: '',
        },
      ],
      status: false, //	网点状态：false-启用，true-禁用
      strategy: {
        autoCheckCancelOrder: false, //是否自动审核取消工单：false-人工审核，true-自动审核
        autoCheckEndOrder: false, //是否自动审核申请结单：false-人工审核，true-自动审核
        autoDispatchOrder: true, //是否自动派单 false：关闭，true：启用,示例值(true)
        enableCreateOrder: true, //是否启用新建工单 false：关闭，true：启用,示例值(true)
        enableScanReceive: true, //是否启用扫码收款 false：不启用，true：启用,示例值(true)
        enableUpdateSparePrice: false, //是否启用更改配件价格：false-不允许修改，true-允许修改
        importReceiverVoucher: true, //是否上传收款凭证 false：不用上传，true：必须上传,示例值(true)
        autoSureReceiveOrder: true, // 确认接单策略： false：人工确认，true：自动确认,示例值(true)
        withdrawHandlingFeeStrategy: 1, //提现手续费策略：1-按比例收取，2-每间固定
        handingFeeProportion: 0, //手续费比例，单位为%，当withdrawHandlingFeeStrategy=1时生效
        handingFeeFixedOrder: 0, //每单固定手续费：当withdrawHandlingFeeStrategy=2时生效
        allowWithdrawal: true,
        allowSelectFee: true,
        withdrawEmpRootVos: ['-1'],
        selectFeeEmpRootVos: ['-1'],
        allowManagerHelpWithdraw: false,
        allowUpdateSnCode: true,
      },
      teamType: 1, //团队类型：1-团队，2-个人
      networkTypeIds: [], //分类id集合
      networkTypeNames: [], //分类名称集合
      networkTypeId: '', //网点分类ID
      networkType: '',
      twoNetworkTypeId: '',
      twoNetworkType: '',
      threeNetworkTypeId: '',
      threeNetworkType: '',
    })
  }
  const rules = reactive({
    phone: [
      { required: true, message: '请输入绑定的手机号', trigger: 'blur' },
      { validator: phone(data.value.phone), trigger: 'blur' },
    ],
    networkAgencyId: [{ required: true, message: '请选择网点机构', trigger: 'blur' }],
    name: [
      { required: true, message: '请输入网点名称', trigger: 'blur' },
      { max: 20, message: '长度不超过20个字符', trigger: 'blur' },
    ],
    accountName: [{ required: true, message: '请输入负责人名称', trigger: ['change', 'blur'] }],
    type: [{ required: true, message: '请选择网点类型', trigger: ['change', 'blur'] }],
    province: [{ validator: setProvince(data.value.province), trigger: 'change' }],
    address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  })
  const rules2 = reactive({
    province: [{ validator: setProvince2(data.value.serviceAreas[0].province), trigger: 'change' }],
  })
  // 获取网点机构
  const selectVo = ref({
    limit: 0,
    name: '',
    page: 0,
  })
  const NetworkAgencyList = ref([])
  const getNetworkAgencyListFun = async () => {
    await getNetworkAgencyList(selectVo.value).then((res) => {
      if (res.data.code == 20000) {
        NetworkAgencyList.value = res.data.data.rows
      }
    })
  }
  // 获取分类列表数据
  const dataType = ref([])
  onMounted(() => {
    getNetworkAgencyListFun()
  })
  // 查询账号信息加载
  const queryInfoAccountLoading = ref(false)
  function empPageSelecctList(val) {
    if (!verifyPhone(val)) {
      return
    }
    queryInfoAccountLoading.value = true
    // 获取负责人信息
    getInfoAccount(val).then((res) => {
      queryInfoAccountLoading.value = false
      if (res.data.success) {
        if (res.data.data.row.id.length > 0) {
          data.value.accountId = res.data.data.row.id
          data.value.accountName = res.data.data.row.name
          data.value.phone = res.data.data.row.phone
          HMessage.success(infoTip.network.create.getAccountSuccess)
        } else {
          data.value.accountName = ''
          data.value.accountId = null
          isInput.value = false
          HMessageBox.warning('手机查无账号，手动输入该账号名字后自动新建账号！')
        }
      } else {
        HMessageBox.error(res.data.message)
      }
    })
  }
  // // 获取分类类型下拉数据
  // async function networkTypePageSelectList(val) {
  //   loading.value = true
  //   const tem = {
  //     limit: 0,
  //     name: val,
  //     page: 0,
  //   }
  //   await networkTypePageSelect(tem).then((res) => {
  //     modules.value = res.data.data.rows
  //   })
  //   loading.value = false
  // }

  // 工单模块带费用下拉列表查询
  const inputWorkModChange = _.throttle((val: string, index: number) => {
    workModulePricePageSelectList(val, index)
  }, 500)

  const workModulePricePageSelectList = async (val: string, index = 0) => {
    loading.value = true
    const tem = {
      limit: 0,
      name: val,
      page: 0,
    }
    data.value.moduleSettlements[index] = {
      ...data.value.moduleSettlements[index],
      workModulePrice: [],
    }
    const res = await workModulePricePageSelect(tem)
    if (data.value.moduleSettlements[index].workModulePrice) {
      data.value.moduleSettlements[index].workModulePrice = res.data.data.rows
    }
    loading.value = false
  }
  // 新增模块费用
  const onAddItem = async () => {
    data.value.moduleSettlements.push({
      id: null,
      moduleId: null, //	模块ID
      price: null, //网点结算价
      workModulePrice: [],
    })
    await workModulePricePageSelectList('', data.value.moduleSettlements.length - 1)
  }
  // 删除模块费用
  const detelePri = (row, index) => {
    data.value.moduleSettlements = data.value.moduleSettlements.filter((o, index1) => {
      return index1 != index
    })
    if (row.id) {
      data.value.delModuleSettlementIds.push(row.id)
    }
  }
  // 批量填写
  const Allprice = ref()
  const changeAllAllprice = () => {
    data.value.moduleSettlements = data.value.moduleSettlements.map((o) => {
      return { ...o, price: Allprice.value }
    })
  }
  // 保存
  async function addSave(formEl: FormInstance | undefined) {
    if (!formEl) return
    // 校验自定义字段
    let isPass = true
    if (data.value.fieldVals.length > 0) {
      isPass = await formRef2.value.validate(async (valid: boolean) => {
        return valid
      })
    }
    await formEl.validate(async (valid) => {
      if (valid && isPass) {
        loadingSave.value = true
        // 获取保存数据
        data.value.serviceAreas = await addrsDom_ser.value.getSelectAddr()
        if (data.value.networkTypeIds.length > 0) {
          data.value.networkTypeNames = []
          data.value.networkTypeId = ''
          data.value.networkType = ''
          data.value.twoNetworkTypeId = ''
          data.value.twoNetworkType = ''
          data.value.threeNetworkTypeId = ''
          data.value.threeNetworkType = ''
          dataType.value.forEach((item) => {
            if (data.value.networkTypeIds.includes(item.id)) {
              data.value.networkTypeNames.push(item.name)
              data.value.networkTypeId = item.id
              data.value.networkType = item.name
              if (item.childData.length > 0) {
                item.childData.map((item2) => {
                  if (data.value.networkTypeIds.includes(item2.id)) {
                    data.value.networkTypeNames.push(item2.name)
                    data.value.twoNetworkTypeId = item2.id
                    data.value.twoNetworkType = item2.name
                    if (item2.childData.length > 0) {
                      item2.childData.map((item3) => {
                        if (data.value.networkTypeIds.includes(item3.id)) {
                          data.value.networkTypeNames.push(item3.name)
                          data.value.threeNetworkTypeId = item3.id
                          data.value.threeNetworkType = item3.name
                        }
                      })
                    }
                  }
                })
              }
            }
          })
        }
        const dataSave = _.cloneDeep(data.value)
        // 判断是否有自定义字段文件上传
        if (dataSave.fieldVals.length > 0) {
          for (const key in dataSave.fieldVals) {
            const item = dataSave.fieldVals[key]
            if (item.type == 5 || item.type == 6 || item.type == 7) {
              const img = [] //新上传的
              const isImg = [] //已经上传的
              for (const i in item.imgarr) {
                const it = item.imgarr[i]
                if (it.file) {
                  img.push(it.file)
                } else {
                  isImg.push(it)
                }
              }
              if (img.length > 0) {
                if (item.type == 7) {
                  const res = await orderVideoUpload(img)
                  if (res.data.success) {
                    for (let i = 0; i < res.data.data.rows.length; i++) {
                      item.value.push({ id: null, image: res.data.data.rows[i] })
                    }
                  } else {
                    ElMessageBox({
                      message: res.data.message,
                      type: 'error',
                      title: '提示',
                    })
                  }
                } else {
                  const res = await orderAnnexUpload(img)
                  if (res.data.success) {
                    for (let i = 0; i < res.data.data.rows.length; i++) {
                      item.value.push({ id: null, image: res.data.data.rows[i] })
                    }
                  } else {
                    ElMessageBox({
                      message: res.data.message,
                      type: 'error',
                      title: '提示',
                    })
                  }
                }
              }
              item.value = [...isImg, ...item.value]
              if (item.type == 5 || item.type == 6 || item.type == 7) {
                item.value = item.value
              }
            }
          }
        }

        addressValChange2()
        dataSave.fieldVals = dataSave.fieldVals.map((item) => {
          let tem = []
          if (item.type === 5 || item.type === 6 || item.type === 7) {
            tem = item.value.map((o) => {
              return { id: o.id, optValue: o.image }
            })
          } else if (item.type === 4) {
            tem = item.value.map((o) => {
              return { id: null, optValue: o }
            })
          } else {
            tem = [{ id: null, optValue: item.value }]
          }
          return { ...item, optVos: tem }
        })

        // 网点结算 - 新增时没有选择模块名称就将不传递参数到请求体里
        dataSave.moduleSettlements = dataSave.moduleSettlements.filter((item) => {
          if (item.moduleId !== null) {
            return item
          }
        })
        const res = await addNetwork(dataSave)
        loadingSave.value = false
        if (res.data.success) {
          HMessage.success(infoTip.network.create.success)
          formRef.value?.resetFields()
          formRef2.value?.resetFields()
          data.value.moduleSettlements = []
          addrsDom.value?.clearSelectAddr()
          data.value.province = ''
          data.value.city = ''
          data.value.area = ''
          data.value.town = ''
          // refresh()
          TagsViewStore.delView(router.currentRoute.value.path)
          router.push('/net/list')
        } else {
          HMessageBox.error(infoTip.network.create[res.data.code] || res.data.message)
        }
      }
    })
  }
  // 所属地址
  function addressValChange() {
    const addr = addrsDom.value.getSelectAddr()
    data.value.province = addr.province
    data.value.city = addr.city
    data.value.area = addr.area
    data.value.town = addr.town
  }
  // 服务范围地址
  async function addressValChange2() {
    // data.value.serviceAreas[0] = { ...data.value.serviceAreas[0], ...addrsDom_ser.value.getLabel() }
    data.value.serviceAreas = await addrsDom_ser.value.getSelectAddr()
  }

  // 编辑之前的财务信息
  const financialInfoBeforeEdit = ref({
    bandName: '',
    bandNo: '',
    businessLicenseImage: '',
    businessLicenseNo: '',
    cardholderName: '',
    settlementType: 1,
  })

  // 获取新增后的详情
  async function getBeforeNetworkEditSelectData(id: string) {
    loadingSave.value = true
    if (route.params.id) {
      const res = await getBeforeNetworkEditSelect(id)
      if (res.data.code === 20000) {
        const row = res.data.data.row

        if (res.data.data.row.financeVo) {
          financialInfoBeforeEdit.value = res.data.data.row.financeVo
        }

        // 解决服务范围选择了地址后, 后面再查看就不显示之前选择了的地址
        addrs2.value = row.serviceAreas.map((item) => {
          return {
            province: item.province,
            city: item.city,
            area: item.area,
            town: item.town,
          }
        })
        data.value.accountId = row.accountId //网点负责人登录账号ID
        data.value.phone = row.phone
        data.value.accountName = row.accountName
        data.value.address = row.address
        data.value.area = row.area
        data.value.province = row.province
        data.value.contacts = row.contacts
        data.value.businessPhone = row.businessPhone
        data.value.city = row.city
        data.value.town = row.town
        data.value.category = row.category //网点模式：1-内部网点 2-第三方网点,示例值(1)
        data.value.code = row.code //网点编码
        data.value.delModuleSettlementIds = [] //删除的服务模块结算对象ID
        data.value.id = row.id //网点ID，新增不必传，修改必传
        data.value.moduleSettlements = row.moduleSettlements
        data.value.name = row.name //网点名称
        data.value.departmentIds = row.departmentIds
        data.value.shorterName = row.shorterName
        data.value.freeAmountPercentage = row.freeAmountPercentage || 0
        data.value.networkAgencyId = row.networkAgencyId === '0' ? '' : row.networkAgencyId
        data.value.enableStore = row.enableStore
        data.value.networkTypeIds = []
        data.value.networkTypeNames = []
        if (res.data.data.row.networkTypeId != '0') {
          data.value.networkTypeIds.push(res.data.data.row.networkTypeId)
          if (res.data.data.row.twoNetworkTypeId != '0') {
            data.value.networkTypeIds.push(res.data.data.row.twoNetworkTypeId)
            if (res.data.data.row.threeNetworkTypeId != '0') {
              data.value.networkTypeIds.push(res.data.data.row.threeNetworkTypeId)
            }
          }
        }
        if (res.data.data.row.networkType) {
          data.value.networkTypeNames.push(res.data.data.row.networkType)
          if (res.data.data.row.twoNetworkType) {
            data.value.networkTypeNames.push(res.data.data.row.twoNetworkType)
            if (res.data.data.row.threeNetworkType) {
              data.value.networkTypeNames.push(res.data.data.row.threeNetworkType)
            }
          }
        }
        getNetworkTypeOptions('').then(() => {
          netWorktypeOptions.value.forEach((networkType) => {
            if (networkType.id === row.networkTypeId) {
              data.value.networkTypeId = row.networkTypeId //网点分类ID
            }
          })
        })
        data.value.path = row.path //接口路径
        data.value.publicKey = row.publicKey //数据加密公钥
        data.value.serviceAreas = row.serviceAreas
        data.value.status = row.status //	网点状态：false-启用，true-禁用
        data.value.strategy = Object.assign(
          {
            autoDispatchOrder: false,
            enableCreateOrder: false,
            enableScanReceive: false,
            importReceiverVoucher: false,
          },
          { ...row.strategy },
        )
        data.value.teamType = row.teamType

        row.moduleSettlements.map((o, index) => {
          workModulePricePageSelectList('', index)
        })

        if (row.moduleSettlements.length == 0) {
          onAddItem()
        }
        addrs.value = {
          // 地址
          province: row.province,
          city: row.city,
          area: row.area,
          town: row.town,
        }

        //获取自定义字段
        networkFieldSelect().then((res2) => {
          data.value.fieldVals = res2.data.data.rows.map((item) => {
            item['fieldId'] = item.id
            item.id = null
            return item
          })
          data.value.fieldVals = data.value.fieldVals.map((o) => {
            if (o.type == 5 || o.type == 6 || o.type == 7) {
              o.value = []
              o.imgarr = []
            } else if (o.type == 4) {
              o.value = []
            } else {
              o.value = ''
            }
            res.data.data.row.fieldVals.map((item) => {
              if (o.fieldId == item.fieldId) {
                o.id = item.id
                if (item.type == 5 || item.type == 6 || item.type == 7) {
                  const ov = item.optVos.map((vo) => {
                    return { id: vo.id, image: vo.optValue }
                  })
                  o.imgarr = [...ov]
                } else if (item.type == 4) {
                  const ov = item.optVos.map((vo) => vo.optValue)
                  o.value = [...ov]
                } else {
                  o.value = item.optVos.map((vo) => vo.optValue)[0]
                }
              }
            })
            return o
          })

          data.value.fieldVals = data.value.fieldVals.sort(
            (firstItem, secondItem) => firstItem.type - secondItem.type,
          )
        })
      } else {
        ElMessageBox({
          message: res.data.message,
          type: 'error',
          title: '提示',
        })
      }
    }
    loadingSave.value = false
  }
  //获取自定义字段
  const getnetworkFieldSelect = async () => {
    //获取自定义字段
    await networkFieldSelect().then((res) => {
      if (res.data.data.rows.length > 0) {
        data.value.fieldVals = res.data.data.rows.map((o) => {
          o.fieldId = o.id
          o.id = null
          if (o.type == 5 || o.type == 6 || o.type == 7) {
            o.value = []
            o.imgarr = []
          } else if (o.type == 4) {
            o.value = []
          } else {
            o.value = ''
          }
          return o
        })
        data.value.fieldVals = data.value.fieldVals.sort(
          (firstItem, secondItem) => firstItem.type - secondItem.type,
        )
      }
    })
  }
  // 取消
  const onBack = () => {
    router.back()
  }

  // 添加图片
  const handleChange2 = (uploadFile: UploadFile, item) => {
    if (item.uploadSize < uploadFile.size / 1024 / 1024) {
      onExceedSize(item)
      return
    }
    if (item.imgarr.length >= item.uploadQty) {
      onExceedNub(item)
      return
    }
    const { uid, name } = uploadFile.raw
    const tmp = {
      uid,
      name,
      image: window.URL.createObjectURL(uploadFile.raw),
      file: uploadFile.raw,
    }
    item.imgarr.push(tmp)
  }
  const onExceedSize = _.debounce((item) => {
    ElMessageBox({
      message:
        item.type == 5
          ? '图片'
          : item.type == 6
          ? '附件'
          : '视频' + '大小不能超过' + item.uploadSize + 'MB!',
      type: 'error',
      title: '提示',
    })
  }, 10)
  const onExceedNub = _.debounce((item) => {
    ElMessageBox({
      message: `${item.type == 5 ? '图片' : item.type == 6 ? '附件' : '视频'} 数量不能超过 ${
        item.uploadQty
      }!`,
      type: 'error',
      title: '提示',
    })
  }, 10)

  // 删除图片
  const deleteItem2 = (bigindex, index) => {
    data.value.fieldVals = data.value.fieldVals.map((arr, j) => {
      if ((arr.type == 5 || arr.type == 6 || arr.type == 7) && j == bigindex) {
        arr.imgarr = arr.imgarr.filter((o, i) => i != index)
      }
      return arr
    })
  }
  // 查看图片
  const lookFile = (val, tem) => {
    file.value = val
    dialogContract.value = true
    isPdf.value = tem
  }
  //监听查看附件弹窗关闭时销毁 iframe内存
  watch(dialogContract, (n) => {
    if (!n) {
      file.value = ''
    }
  })
  watch(route, async (value) => {
    if (value.name === 'editDetails') {
      if (!route.params.id) {
        initData()
      }
    }
  })

  return {
    rules,
    isPdf,
    data,
    file,
    addrs,
    rules2,
    addrs2,
    defined,
    modules,
    formRef,
    isInput,
    loading,
    Allprice,
    selectVo,
    formRef2,
    typeList,
    dataType,
    addrsDom,
    loadingSave,
    categoryList,
    addrsDom_ser,
    dialogContract,
    NetworkAgencyList,
    inputWorkModChange,
    queryInfoAccountLoading,
    financialInfoBeforeEdit,
    onBack,
    addSave,
    lookFile,
    detelePri,
    onAddItem,
    deleteItem2,
    handleChange2,
    addressValChange,
    addressValChange2,
    // networkTypePageSelectList,
    changeAllAllprice,
    empPageSelecctList,
    getnetworkFieldSelect,
    getNetworkAgencyListFun,
    getBeforeNetworkEditSelectData,
  }
}
